package cn.itcast.n4_共享模型_管程;

import lombok.extern.slf4j.Slf4j;

/**
 * @program: juc
 * @description:
 * @author: flyduck
 * @create: 2024-09-11 09:38
 **/
@Slf4j(topic = "c.Test02_使用synchronized解问题_一个自增一个自减结果不为0")
public class Test02_使用synchronized解问题_一个自增一个自减结果不为0 {
    static int counter = 0;
    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (lock) {
                    counter++;
                }
            }
        },"t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                synchronized (lock) {
                    counter--;
                }
            }
        },"t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("结果为:{}", counter);//0

    }
}
